package com.zhuannimei.ui;

import java.util.ArrayList;
import java.util.List;

import android.os.Bundle;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ListView;

import com.lidroid.xutils.util.LogUtils;
import com.zhuannimei.GlobalApplication;
import com.zhuannimei.R;
import com.zhuannimei.adapter.MessageAdapter;
import com.zhuannimei.domain.ZnmMessage;
import com.zhuannimei.service.AsyncDataLoader;
import com.zhuannimei.service.AsyncDataLoader.Callback;
import com.zhuannimei.utility.MessageTypes;

public class MessageActivity extends BaseActivity {

	private ListView mListView;
	private List<ZnmMessage> mList = new ArrayList<ZnmMessage>();;
	private MessageAdapter mAdapter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.message);
		mListView = (ListView) findViewById(R.id.message_LV);
		initData();
	}

	@Override
	protected void onStart() {
		super.onStart();
		mTitlePane.setTitle("消息中心");
		mTitlePane.getLeftButton().setVisibility(View.VISIBLE);
		mTitlePane.getRightButton().setVisibility(View.VISIBLE);
		mTitlePane.setRightButtonTextAndListener("清空", new OnClickListener() {
			@Override
			public void onClick(View v) {
				delAllMsg();
			}
		});
		mTitlePane.setLeftButtonTextAndListener("返回", new OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();
			}
		});
	}

	private void delAllMsg() {
		// 清空
		LogUtils.i("清空");
		GlobalApplication.appDB.deleteByWhere(ZnmMessage.class, null);
		if (mList != null) {
			mList.clear();
		}
		mAdapter.notifyDataSetChanged();
	}

	@Override
	protected void handleMsg(Message msg) {
		super.handleMsg(msg);
		switch (msg.what) {
		case MessageTypes.UPDATE_MESSAGE_LIST:
			LogUtils.i("执行了");
			ZnmMessage jm = (ZnmMessage) msg.obj;
			LogUtils.i("消息内容==" + jm.getContent());
			mList.add(jm);
			mAdapter.notifyDataSetChanged();
			break;

		default:
			break;
		}
	}

	private void initData() {
		new AsyncDataLoader(new Callback() {
			@Override
			public void onStart() {
				List<ZnmMessage> list = GlobalApplication.appDB
						.findAll(ZnmMessage.class);
				if (list != null && list.size() != 0) {
					mList.clear();
					mList.addAll(list);
				}
			}

			@Override
			public void onPrepare() {
				// pd.setMsg("正在更新……");
				// pd.show();
				showLoadingDialog("正在更新……");
			}

			@Override
			public void onFinish() {
				// pd.cancel();
				// 刷新界面
				if (mAdapter == null) {
					mAdapter = new MessageAdapter(getApplicationContext(),
							mList);
				}
				mListView.setFastScrollEnabled(true);
				mListView.setAdapter(mAdapter);
				dismissLoadingDialog();
			}
		}).execute();
	}
}
